package com.base.themvx.widget

import android.content.Context
import android.util.AttributeSet
import androidx.core.view.isVisible
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieOnCompositionLoadedListener
import com.airbnb.lottie.LottieProperty
import com.airbnb.lottie.model.KeyPath
import com.airbnb.lottie.value.SimpleLottieValueCallback
import com.base.themvx.AppLog

/**
 ******************(^_^)***********************<br>
 * Author: fee<br>
 * <P>DESC:
 * 对 Lottie 动画控件的继承封装
 * </p>
 * ******************(^_^)***********************
 */
class LocalLottieAnimView(context: Context, attributeSet: AttributeSet?) :
    LottieAnimationView(context, attributeSet), LottieOnCompositionLoadedListener,
    IAnimViewHandler {

    var mIsNeedCancelAnimOnDetached = true

    var mTag: String = ""

    override fun setAnimation(rawRes: Int) {
        if (rawRes == 0) {
            return
        }
        super.setAnimation(rawRes)
    }

    override fun playAnimation() {
        super.playAnimation()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        AppLog.e("LocalLottieAnimView", "--> onDetachedFromWindow() mTag = $mTag")
        if (mIsNeedCancelAnimOnDetached && isAnimating) {
            cancelAnimation()
        }
    }

    fun addListener() {
        addLottieOnCompositionLoadedListener(this)
    }

    var mTintColor: Int = 0
        set(value) {
            field = value
            if (value != 0) {
                addListener()
            }
        }

    override fun onCompositionLoaded(composition: LottieComposition?) {
        resolveKeyPath(KeyPath(("**"))).forEach { path ->
            AppLog.i("fee", "--> onCompositionLoaded()  path = ${path.keysToString()}")
        }
        val fillKeyPath = KeyPath("填充 1")
        addValueCallback(fillKeyPath, LottieProperty.COLOR,
            SimpleLottieValueCallback {
                AppLog.e("fee", "-->onCompositionLoaded() fill...  ")
                return@SimpleLottieValueCallback mTintColor
            })

        val strokeKeypath = KeyPath("ADBE Vector Graphic - Stroke", "描边 1")
        addValueCallback(strokeKeypath, LottieProperty.STROKE_COLOR, SimpleLottieValueCallback {
            return@SimpleLottieValueCallback mTintColor
        })
    }

    override fun isAniming(): Boolean {
        return isAnimating
    }

    override fun playAnim() {
        playAnimation()
    }

    override fun cancelAnim() {
        cancelAnimation()
    }

    override fun isViewVisible(): Boolean {
        return isVisible
    }
}